package com.zhentao.conf;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
@Aspect
@Slf4j
public class LogConfig {
    //切入点表达式 -controlelr每一个方法里面
    @Pointcut("execution(* com.zhentao.controller.*.*(..)  )")
    public void pointcut(){

    }
    //环绕通知
    @SneakyThrows
    @Around(("pointcut()"))
    public Object aspectLog(ProceedingJoinPoint joinPoint){
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //访问路径
        String uri = request.getRequestURI();
        //IP地址
        String ip = request.getRemoteAddr();
        //请求方式
        String method = request.getMethod();
        //类名
        String cls = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        //参数
        Object[] args = joinPoint.getArgs();
        //执行结果
        Object object = joinPoint.proceed();  //放行的方法

        //保持日志
        log.info("ip:{}\t url:{}\t method:{}\t cls:{}\t methodName:{} \t,参数：{}" +
                "\t result:{} " ,ip,uri,method,cls,methodName,args,object);

        //某些记录需要保存数据库
        return object;
    }

}
